/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rcnss.data;
import java.io.Serializable;
import java.sql.*;

/**
 *
 * @author Guesmi
 */
public class ConnexionBD implements Serializable {
    private static Connection dbCon = null;
    private Statement stmt;

    private void makeConnection() throws ClassNotFoundException, SQLException {
        if(dbCon != null)
            return;
        Class.forName("oracle.jdbc.driver.OracleDriver");
        dbCon = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "projet2010", "2010");
        System.out.println("ops connected.. ;)");
    }

    public ResultSet executerSelect(String req) throws SQLException, ClassNotFoundException {
            makeConnection();
            stmt = dbCon.createStatement();
            System.out.println("executer Select: " +req);
            return stmt.executeQuery(req);
    }

    public int executeUpdate(String req) throws SQLException, ClassNotFoundException {
        makeConnection();
        stmt = dbCon.createStatement();
        System.out.println("executer INSERT: "+req);
        return stmt.executeUpdate(req);
    }
    /*
     * Description: This Function is for Execute a simple Insert Statement
     * Table: the name of the Table where we go to Insert into
     * args...: The list of the columns and values to insert
     */
    public void InsertNewLine(String Table, String ... args) throws Exception
    {
        if(args.length % 2 != 0)
        {
            throw new Exception("Number of parameter is not correct");
        }
        String req = " INSERT INTO "+ Table +" ( ";
        String reqName = args[0];
        String reqValue = args[1];
        for(int i =2; i<args.length;i+=2){
            reqName += ","+args[i];
            reqValue +=","+ args[i+1];
        }
        req += reqName + ") VALUES (";
        req += reqValue + ")";
        
        this.executeUpdate(req);
    }
/*
 * C'est une fonction pour faire la modification d'un tableau donnee ..
 * Table : c'est le tableau a modifier
 * args...:l'ensemble des arguments a entrees a condition que les arguments soit
 * ordonnees de tel facon que le 1er soit le colone et 2eme soit la valeur de cet colone
 * et ect ..
 */
    public void UpdateLine ( String Table ,int ID, String ... args) throws Exception
    {
        if(args.length % 2 != 0)
        {
            throw new Exception("Number of parameter is not correct");
        }

        String req = "Update "+ Table + " SET " ;
        String reqColone = args[0];
        String reqValue = "="+args[1]+"";
        String reqres = reqColone + reqValue ;
        for(int i=2; i<args.length; i+=2)
        {
            reqres += "," +args[i]+ "="+ args[i+1]+"";
        }
        req += reqres+ " where UTL_MAT ="+ ID +"";
        this.executeUpdate(req);

    }


}
